import smtplib
import time
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.application import MIMEApplication
from util.logger import Logger
from util.conf import ReadConfig
Log = Logger().logger


class TestMail(object):

    def __init__(self):
        self.config = ReadConfig()


    def take_messages(self):    #文件内容
        self.msg = MIMEMultipart()
        self.msg['Subject'] = '测试报告主题'  # 邮件的标题
        self.msg['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')

        with open(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'result', 'reports.html'), 'rb') as f:
            mailbody = f.read()  # 读取测试报告的内容
        html = MIMEText(mailbody, _subtype='html', _charset='utf-8')  # 将测试报告的内容放在 邮件的正文当中
        self.msg.attach(html)  # 将html附加在msg里

        # html附件    下面是将测试报告放在附件中发送
        # att1 = MIMEText(mailbody, 'base64', 'gb2312')
        # att1["Content-Type"] = 'application/octet-stream'
        # att1["Content-Disposition"] = 'attachment; filename="test_response.html"'  # 这里的filename可以任意写，写什么名字，附件的名字就是什么
        # self.msg.attach(att1)

        htmlFile = '测试报告.html'
        htmlApart = MIMEApplication(open(os.path.join(os.path.abspath(os.path.dirname(os.path.dirname(__file__))), 'result', 'reports.html'), 'rb').read())
        htmlApart.add_header('Content-Disposition', 'attachment', filename=htmlFile)
        self.msg.attach(htmlApart)



    def send_mail(self):
        self.take_messages()
        self.msg['from'] = self.config.get('mail', 'sender')  # 发送邮件的人
        self.msg['to'] = self.config.get('mail', 'receivers')  # 收件人和发送人必须这里定义一下，执行才不会报错。
        # smtp = smtplib.SMTP('smtp.163.com', 25)  # 连接服务器
        smtp = smtplib.SMTP()
        smtp.connect(self.config.get('mail', 'mail_host'))
        smtp.login(self.config.get('mail', 'mail_user'), self.config.get('mail', 'mail_pass'))  # 登录的用户名和密码（注意密码是设置客户端授权码，因为使用用户密码不稳听，有时无法认证成功，导致登录不上，故无法发送邮件。）
        smtp.sendmail(self.msg['from'], self.msg['to'], self.msg.as_string())  # 发送邮件
        smtp.close()
        print('sendmail success')
        Log.info('======================>邮件发送成功，收件人：{}<======================='.format(self.msg['to']))



if __name__ == "__main__":
    send = TestMail()
    send.send_mail()

